<template>
  <div>
    <el-dialog
      title="图片管理"
      :visible.sync="imageModal"
      width="80%"
      top="5vh"
    >
      <el-container style="position: relative; height: 70vh">
        <el-header class="d-flex align-items-center">
          <div class="d-flex mr-auto align-items-center">
            <el-select
              class="mr-2"
              v-model="searchForm.order"
              placeholder="请选择图片排序方式"
              size="medium"
              style="width: 200px"
            >
              <el-option
                v-for="(item, index) in searchForm"
                :key="index"
                :label="item.order"
                :value="item.keywords"
              >
              </el-option>
            </el-select>
            <el-input
              class="mr-2"
              style="width: 200px"
              placeholder="请输入相册名称"
              v-model="searchForm.keywords"
            >
            </el-input>
            <el-button type="success" size="medium">搜索</el-button>
          </div>
        </el-header>
        <el-container>
          <!-- 侧边栏 -->
          <el-aside
            width="200px"
            class="elAside bg-white border-right"
            style="padding-left: 20px"
          >
            <ul class="list-group list-group-flush">
              <li
                class="list-group-item d-flex align-items-center"
                :class="{ 'sum-active': index === albumIndex }"
                @click.stop="changeAlbum(index)"
                v-for="(item, index) in album"
                :key="index"
              >
                {{ item.name }}
                <span class="btn btn-light btn-sm border ml-auto">
                  {{ item.order }}
                </span>
              </li>
            </ul>
          </el-aside>
          <!-- 主体内容部分 -->
          <el-container class="mainContainer">
            <el-main>
              <!-- 相册主内容 -->
              <el-row :gutter="10">
                <el-col
                  class="mx-2"
                  :span="24"
                  :lg="4"
                  :md="6"
                  :sm="8"
                  v-for="(item, index) in imgList"
                  :key="index"
                >
                  <el-card
                    class="box-card position-relative mb-2"
                    style="width: 140px"
                    :body-style="{ padding: 0 }"
                  >
                    <div
                      class="border"
                      style="height: 140px"
                      :class="{ 'border-danger': item.isCheck }"
                    >
                      <span
                        class="badge badge-danger position-absolute"
                        v-show="item.isCheck"
                        style="right: 0; top: 0"
                        >{{ item.checkOrder }}</span
                      >
                      <div>
                        <img
                          :src="item.url"
                          style="height: 100px"
                          class="w-100"
                          @click="chooseImage(item)"
                        />
                        <div class="w-100 imgText">{{ item.name }}</div>
                      </div>
                      <el-button-group class="btnGroup">
                        <el-button
                          icon="el-icon-view"
                          size="mini"
                          @click="previewImg(item)"
                        ></el-button>
                        <el-button
                          icon="el-icon-edit"
                          size="mini"
                          @click="editImage(item, index)"
                        ></el-button>
                        <el-button
                          icon="el-icon-delete"
                          size="mini"
                          @click="delImage(index)"
                        ></el-button>
                      </el-button-group>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
              <!-- /相册主内容 -->
            </el-main>
          </el-container>
        </el-container>
        <el-footer class="d-flex align-items-center p-0 border-top">
          <div class="border-right" style="width: 200px; padding-left: 20px">
            <el-button-group>
              <el-button size="mini">&lt;上一页</el-button>
              <el-button size="mini">下一页&gt;</el-button>
            </el-button-group>
          </div>
          <div class="pl-2" style="margin-top: 0px">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 50]"
              :page-size="100"
              layout="total, sizes, prev, pager, next, jumper"
              :total="400"
            >
            </el-pagination>
          </div>
        </el-footer>
      </el-container>
      <div slot="footer">
        <el-button @click="hide">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 预览图片 -->
    <el-dialog :visible.sync="previewModal">
      <div style="margin: -60px;-20px;-40px;-20px">
        <img :src="previewImage" class="w-100" />
      </div>
    </el-dialog>
    <!-- /预览图片 -->
  </div>
</template>
<script>
export default {
  data() {
    return {
      imageModal: false,
      callback: false,
      searchForm: [
        {
          order: "排序1",
          keywords: "黄金糕",
        },
        {
          order: "排序2",
          keywords: "双皮奶",
        },
      ],
      album: [],
      albumIndex: 0,
      albumVisible: false,
      createAlbumIndex: -1,
      rules: {
        name: [{ required: true, message: "请输入相册名", trigger: "blur" }],
        order: [
          { required: true, message: "请输入序号", trigger: "blur" },
          {
            pattern: /^[0-9]{1,15}$/,
            message: "序号不符合要求",
            trigger: "blur",
          },
        ],
      },
      previewModal: false,
      imgList: [],
      previewImage: "",
      currentPage: 1,
      chooseList: [],
    };
  },
  components: {},
  props: {
    //   最多选择的图片数量
    max: {
      type: Number,
      default: 9,
    },
  },
  created() {
    this.__initAlbum();
  },

  methods: {
    show(callback) {
      this.callback = callback;
      this.imageModal = true;
      //   清空选择列表
      this.unChoose();
    },
    confirm() {
      // 选中的图片
      if (typeof this.callback === "function") {
        this.callback(this.chooseList);
      }
      this.hide();
    },
    hide() {
      this.imageModal = false;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    // 删除图片
    delImage(index) {
      this.$confirm(" 确定是否要删除图片?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.imgList.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 修改图片名称
    editImage(item, index) {
      this.$prompt("请输入新名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValue: item.name,
        inputValidator(val) {
          if (val == "") {
            return "图片名不能为空";
          }
        },
      })
        .then(({ value }) => {
          (item.name = value),
            this.$message({
              type: "success",
              message: "新名称是: " + value,
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },
    // 预览图片
    previewImg(item) {
      this.previewImage = item.url;
      this.previewModal = true;
    },
    // 点击切换相册
    changeAlbum(index) {
      this.albumIndex = index;
    },
    // 初始化相册
    __initAlbum() {
      let arr = [];
      for (let index = 0; index < 20; index++) {
        arr.push({
          name: "相册" + index,
          order: Math.floor(Math.random() * 100),
        });
      }
      this.album = arr;
      // 生成相片列表
      for (let index = 0; index < 20; index++) {
        this.imgList.push({
          id: index,
          url: "https://tangzhe123-com.oss-cn-shenzhen.aliyuncs.com/Appstatic/qsbk/demo/datapic/40.jpg",
          name: "图片" + (index + 1 - 0),
          isCheck: false,
          checkOrder: 0,
        });
      }
    },
    chooseImage(item) {
      // 未选中
      if (!item.isCheck) {
        //   限制选择的图片数量
        if (this.chooseList.length >= this.max) {
          return this.$message({
            message: "不能超过" + this.max + "张图片",
            type: "warning",
          });
        }
        this.chooseList.push({
          id: item.id,
          url: item.url,
        });
        item.isCheck = true;
        item.checkOrder = this.chooseList.length;
        return;
      }
      // 已选中
      // 找到取消选中的index
      let i = this.chooseList.findIndex((v) => v.id === item.id);
      if (i === -1) return;
      // 重新计算序号
      let length = this.chooseList.length;
      if (i + 1 < length) {
        // 从第i个开始循环 后面的才需要重新计算序号
        for (let j = i; j < length; j++) {
          let no = this.imgList.findIndex(
            (v) => v.id === this.chooseList[j].id
          );
          if (no > -1) {
            this.imgList[no].checkOrder--;
          }
        }
      }
      // 重新计算数组长度
      this.chooseList.splice(i, 1);
      item.isCheck = false;
      item.checkOrder = 0;
    },
    // 取消选择图片
    unChoose() {
      this.imgList.forEach((img) => {
        // 找到选择列表有的图片的索引
        let i = this.chooseList.findIndex((v) => {
          return v.id === img.id;
        });
        if (i > -1) {
          // 从选择列表中删除
          this.chooseList.splice(i, 1);
          img.isCheck = false;
          img.checkOrder = 0;
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.elAside {
  position: absolute;
  top: 60px;
  bottom: 60px;
  left: 0;
}
.mainContainer {
  position: absolute;
  top: 60px;
  bottom: 60px;
  left: 200px;
  right: 0;
}
.imgText {
  position: absolute;
  margin-top: -25px;
  text-align: left;
  padding-left: 10px;
  height: 25px;
  line-height: 25px;
  color: white;
  background: rgba(0, 0, 0, 0.5);
}
.btnGroup {
  position: absolute;
  width: 140px;
  margin-top: 5px;
  margin-left: 5px;
}
.sum-active {
  color: #67c23a !important;
  background-color: #f0f9eb !important;
  border-color: #c2e7b0 !important;
}
/deep/.el-dialog__wrapper {
  .el-dialog__body {
    padding-top: 0 !important;
    padding-bottom: 0 !important;
  }
}
</style>
